package cn.touna.jss.util;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import java.util.SortedMap;

/**
 * 公共方法
 */
public class Common {

    private static final Logger logger = LogManager.getLogger(Common.class);

    private final static String key = "verificationCodeTest";

    /**
     * 获取签名
     *
     * @param parameters
     * @return
     */
    public static String getSign(String parameters, String timestamp) {
        StringBuilder sb = new StringBuilder();
        sb.append(parameters).append(key).append(timestamp);
        return MD5(sb.toString());

    }

    /**
     * MD5 加密
     */
    public static String MD5(String str) {
        MessageDigest messageDigest = null;
        try {
            messageDigest = MessageDigest.getInstance("MD5");
            messageDigest.reset();
            messageDigest.update(str.getBytes("UTF-8"));

            byte[] byteArray = messageDigest.digest();
            StringBuffer md5StrBuff = new StringBuffer();
            for (int i = 0; i < byteArray.length; i++) {
                if (Integer.toHexString(0xFF & byteArray[i]).length() == 1)
                    md5StrBuff.append("0").append(
                            Integer.toHexString(0xFF & byteArray[i]));
                else
                    md5StrBuff.append(Integer.toHexString(0xFF & byteArray[i]));
            }
            return md5StrBuff.toString();
        } catch (NoSuchAlgorithmException e) {
            logger.info("MD5 NoSuchAlgorithmException caught!");
        } catch (UnsupportedEncodingException e) {
            logger.info("MD5 UnsupportedEncodingException caught!");
        }
        return null;
    }

    @SuppressWarnings("rawtypes")
    public static String generateSign(SortedMap parameters, String api_key) {
        StringBuffer sb = new StringBuffer();
        Set es = parameters.entrySet();
        Iterator it = es.iterator();
        while (it.hasNext()) {
            Map.Entry entry = (Map.Entry) it.next();
            String k = (String) entry.getKey();
            Object v = entry.getValue();
            if (null != v && !"".equals(v)
                    && !"sign".equals(k) && !"key".equals(k)) {
                sb.append(k + "=" + v + "&");
            }
        }
        sb.append("key=" + api_key);
        String sign = MD5(sb.toString()).toUpperCase();
        return sign;
    }

}
